package com.testmanager.testmananger.shuiyou.szjk.service;

import com.alibaba.fastjson.JSONObject;
import com.testmanager.testmananger.shuiyou.szjk.repository.ZipTypeRepository;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j
public class SendZipService {

    @Autowired
    ZipTypeRepository zipTypeRepository;
    /**
     * ziptype ,path
     *
     * @return
     */

    public ResponseEntity send(long ziptypeid,String path) {
        /*jsonObject.put("path",trueFileName);
        jsonObject.put("filename",fileName);*/
        String url = zipTypeRepository.findById(ziptypeid).getUrl();
        String name = System.currentTimeMillis()+ ".zip";
        String rep = "";
        try {
            rep = send(url,path,name);
            log.info(rep);
            return  ResponseEntity.ok(JSONObject.parse(rep));
        } catch (Exception e) {


            log.error(e.getMessage());
            return ResponseEntity.ok(e.toString());
        }

    }




   public  String send(String url, String filePath, String fileName) throws Exception {

        OkHttpClient client = new OkHttpClient();
        RequestBody cookieRequestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
                "username=szjk&password=szjk");  //username=szjk&password=sjfx
        Request cookieRequest = new Request.Builder()
                .url("http://10.199.137.118:5038/login.action") // 局端：http://10.199.137.118:5038/login.action   云端：http://10.199.137.130:8080/login.action
                .post(cookieRequestBody)
                .build();
        Response login =client.newCall(cookieRequest).execute();

        System.out.println(login.header("Set-Cookie"));

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName,
                        RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath)))
                .build();

        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + UUID.randomUUID())
                .header("Cookie",login.header("Set-Cookie"))
                .url(url)
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
       // log.info(response.body().string());

        return response.body().string();
    }

}
